package com.test.services;

import java.util.ArrayList;
import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

/**
 * @author Blackvault
 * 
 */
public class LoginUserService {

	private static final String TAG = "LoginUserService";
	private String formatedQueryResult = null;

	// Method to Validate the User.
	// Username and Password passed in via the User entered EditViews on the
	// LoginActivity.
	// The two parameters are added to ArrayList to form postParameters for PHP
	// Script.
	// Call to HttpClientService with postParameters. Result is retutned then
	// Formatted and substringed.
	// Result is returned.
	public String ValidateUser(String username, String password) {

		final String un = username;
		final String pw = password;

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("username", un));
		Log.d(TAG, "Post Parameter Username " + un);
		postParameters.add(new BasicNameValuePair("password", pw));
		Log.d(TAG, "Post Parameter password " + pw);

		String queryResult = null;
		try {
			queryResult = HttpClientService.executeHttpPost(
					"http://blackvault.net63.net/login.php", postParameters);

			Log.d(TAG, "Query Result " + queryResult);

			formatedQueryResult = queryResult.toString();
			formatedQueryResult = formatedQueryResult.replaceAll("\\s+", "");
			formatedQueryResult = formatedQueryResult.substring(0, 1);

			Log.d(TAG, "Formatted Query Result " + formatedQueryResult);

			if (formatedQueryResult.equals("1")) {
				Log.d(TAG, "Login Successful");

			} else {
				Log.d(TAG, "Login Unsuccessful");
			}

		} catch (HttpException ex) {
			Log.e(TAG, "HTTP error " + ex.toString());
		} catch (Exception e) {
			Log.e(TAG, "Exception Error " + e.toString());
		}

		return formatedQueryResult;
	}
}
